package com.qianbao.qianbaobusiness.ui.webview;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;

import com.androidbase.dialog.MessageDialog;
import com.androidbase.utils.RxUtils;
import com.baseandroid.retrofit.RxObserver;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import today.youcanbe.scansdk.ScanLiveness;
import today.youcanbe.scansdk.ScanSdk;

public class ScanLivenessUtil {

    private final RxPermissions rxPermissions;
    private Activity activity;
    private MyScanListener scanListener;
    private ProgressDialog loadingDialog;
    private byte[] scanImg;
    //活体识别结果存放路径
    private String mSavePath = Environment.getExternalStorageDirectory()
            .getPath() + "/sensetime/";
    private ScanLiveness scanLiveness;
    private String imageNo;

    public ScanLivenessUtil(Activity activity, MyScanListener scanListener) {
        this.activity = activity;
        this.scanListener = scanListener;
        this.rxPermissions = new RxPermissions(activity);
    }

    public boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
        return scanLiveness.handleActivityResult(requestCode, resultCode, data);
    }

    public void applyScanLiveness() {
        new RxPermissions(activity).request(Manifest.permission.CAMERA)
                .compose(RxUtils.<Boolean>applySchedulersLifeCycle((RxAppCompatActivity) activity))
                .subscribe(new RxObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean granted) {
                        if (granted) {
                            startScanLiveness();
                        } else {
                            MessageDialog.goSettingPermission(activity, "操作需要拍照权限，请进行权限设置允许拍照");
                        }
                    }
                });
    }

    /**
     * 开启人脸认证
     */
    private void startScanLiveness() {
        File folder = new File(mSavePath);
        if (folder.exists()) {
            File[] f = folder.listFiles();
            if (f != null) {
                for (File ff : f) {
                    ff.delete();
                }
            }
        }
        final ScanLiveness.ScanLivenessPms scanLivenessPms = new ScanLiveness.ScanLivenessPms(mSavePath);
        scanLivenessPms.scanDetects = new ScanLiveness.ScanLivenessPms.ScanDetect[]{ScanLiveness.ScanLivenessPms.ScanDetect.Blink, ScanLiveness.ScanLivenessPms.ScanDetect.Mouth, ScanLiveness.ScanLivenessPms.ScanDetect.Nod, ScanLiveness.ScanLivenessPms.ScanDetect.Yaw};
        scanLiveness = new ScanLiveness(activity, new ScanSdk.ScanListener<List<byte[]>>() {
            @Override
            public void onScanSucceed(List<byte[]> scanInfo) {
                if (scanInfo == null) {
                    return;
                }
                loadingDialog = ProgressDialog.show(activity, "", "识别中...");
                //默认取出第一张转成base64格式上传服务器存储
                if (scanInfo.size() > 0) {
                    scanImg = scanInfo.get(0);
                }
                //图片转Base64
                String imgBase64 = new String(Base64.encode(scanImg, Base64.NO_WRAP));
                imgBase64 = imgBase64.replaceAll("\r", "").replaceAll("\n", "");

                // 二进制文件转byte字符串
                File binaryFile = new File(mSavePath + "livenessResult");
                String imgFileStr = new String(encodeBase64File(binaryFile));

                if (!TextUtils.isEmpty(imgBase64) && !TextUtils.isEmpty(imgFileStr)) {
                    if (scanListener != null) {
                        scanListener.onScanSucceed(imgBase64, imgFileStr);
                    }
                } else {
                    if (scanListener != null) {
                        scanListener.onScanFail(5001, "base64为空");
                    }
                }
                loadingDialog.cancel();
            }

            @Override
            public void onScanFail(int errorCode, String errorMessage) {
                if (scanListener != null) {
                    scanListener.onScanFail(errorCode, errorMessage);
                }
            }
        });
        scanLiveness.starScan(scanLivenessPms);
    }


    public interface MyScanListener {
        void onScanSucceed(String imgBase64, String imgFileStr);

        void onScanFail(int errorCode, String errorMessage);
    }

    public static String encodeBase64File(File file) {
        FileInputStream inputFile = null;
        try {
            inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            inputFile.close();
            String imgfilebase64 = new String(Base64.encode(buffer, Base64.NO_WRAP));
            return imgfilebase64.replaceAll("\r", "").replaceAll("\n", "");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
